package com.cby.android.olive.storage

import android.content.Context
import android.content.SharedPreferences
import android.os.Parcelable


/**
 * Description:AbsPrefences
 *
 * @author chenbaoyang
 * @create 2023/6/10 11:24
 */
abstract class AbsPreferences {

    private val defaultPrefName = "olive"

    private var preferences: SharedPreferences? = null
    private var editor: SharedPreferences.Editor? = null


    abstract fun fileName(): String?

    private fun getPreferences(context: Context): SharedPreferences? {
        if (preferences == null) {
            preferences = context.getSharedPreferences(context.packageName +"-" + (fileName()?:defaultPrefName), Context.MODE_PRIVATE)
        }
        return preferences
    }


    private fun getEditor(context: Context): SharedPreferences.Editor? {
        if (editor == null) {
            editor = getPreferences(context)!!.edit()
        }
        return editor
    }

    fun putBoolean(context: Context, key: String?, value: Boolean) {
        getEditor(context)!!.putBoolean(key, value).apply()
    }

    fun putInt(context: Context, key: String?, value: Int) {
        getEditor(context)!!.putInt(key, value).apply()
    }

    fun putString(context: Context, key: String?, value: String?) {
        getEditor(context)!!.putString(key, value).apply()
    }

    fun putLong(context: Context, key: String?, value: Long) {
        getEditor(context)!!.putLong(key, value).apply()
    }

    fun putFloat(context: Context, key: String?, value: Float) {
        getEditor(context)!!.putFloat(key, value).apply()
    }

    fun getBoolean(context: Context, key: String?, defaultValue: Boolean): Boolean {
        return getPreferences(context)!!.getBoolean(key, defaultValue)
    }

    fun getInt(context: Context, key: String?, defaultValue: Int): Int {
        return getPreferences(context)!!.getInt(key, defaultValue)
    }

    fun getString(context: Context, key: String?, defaultValue: String?): String? {
        return getPreferences(context)!!.getString(key, defaultValue)
    }

    fun getString(context: Context, key: String?, defaultValue: Long): Long {
        return getPreferences(context)!!.getLong(key, defaultValue)
    }

    fun getFloat(context: Context, key: String?, defaultValue: Float): Float {
        return getPreferences(context)!!.getFloat(key, defaultValue)
    }
}